import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter_notification_listener/flutter_notification_listener.dart';
import 'package:wechat_msg_listener/model/wechat_message.dart';

class WeChatMessageListener extends StatefulWidget {
  const WeChatMessageListener({super.key});

  @override
  _WeChatMessageListenerState createState() => _WeChatMessageListenerState();
}

class _WeChatMessageListenerState extends State<WeChatMessageListener> {
  List<WeChatMessage> weChatMessageList = [];
  late final AssetsAudioPlayer audioPlayer;
  @override
  void initState() {
    super.initState();
    audioPlayer = AssetsAudioPlayer();
    initPlayAudio();
    initPlatformState();
    checkPermission();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('微信消息通知'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('正在监听微信消息...'),
                TextButton(
                    onPressed: clearMessageList, child: const Text('删除消息记录')),
              ],
            ),
            Expanded(
              child: ListView.separated(
                itemCount: weChatMessageList.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Row(
                      children: [
                        Text(weChatMessageList[index].title),
                        const SizedBox(width: 20),
                        Text(weChatMessageList[index].timeStr,
                            style: const TextStyle(fontSize: 12)),
                      ],
                    ),
                    subtitle: Text(weChatMessageList[index].text),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return const Divider();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> initPlayAudio() async {
    await audioPlayer.open(
      Audio('assets/info.wav'),
    );
  }

  void checkPermission() async {
    var hasPermission = await NotificationsListener.hasPermission;
    if (!hasPermission!) {
      NotificationsListener.openPermissionSettings();
      return;
    }

    var isR = await NotificationsListener.isRunning;
    if (!isR!) {
      await NotificationsListener.startService();
    }
  }

  void onDataListener(NotificationEvent event) {
   
    //{"infoText":null,"canTap":true,"title":"道通_李林峄","subText":null,"uid":10305,"showWhen":true,"package_name":"com.tencent.mm","text":"啥","id":1984369520,"_id":"754e9be83470e","actions":null,"channelId":"message_channel_1659502588942","key":"0|com.tencent.mm|1984369520|null|10305","timestamp":1682661956303,"hasLargeIcon":true}

    WeChatMessage weChatMessage = WeChatMessage.parse(event);
    if (weChatMessage.packageName == targetPackageName) {
      //判断是否包含关键字
      final isTextContainsKeyWord = targetKeyWordList
              .indexWhere((element) => weChatMessage.text.contains(element)) !=
          -1;
      if (isTextContainsKeyWord) {
        setState(() {
          weChatMessageList.add(weChatMessage);
        });
        playAudio();
      }
    }
  }

  testData() {
    final json = {
      "infoText": null,
      "canTap": true,
      "title": "道通_李林峄",
      "subText": null,
      "uid": 10305,
      "showWhen": true,
      "package_name": "com.tencent.mm",
      "text": "啥",
      "id": 1984369520,
      "_id": "754e9be83470e",
      "actions": null,
      "channelId": "message_channel_1659502588942",
      "key": "0|com.tencent.mm|1984369520|null|10305",
      "timestamp": 1682661956303,
      "hasLargeIcon": true
    };
    for (var i = 0; i < 20; i++) {
      weChatMessageList.add(WeChatMessage.fromJson(json));
    }
  }

  Future<void> initPlatformState() async {
    NotificationsListener.initialize();
    // register you event handler in the ui logic.
    NotificationsListener.receivePort?.listen((evt) => onDataListener(evt));
  }

  ///清除消息记录
  void clearMessageList() {
    setState(() {
      weChatMessageList.clear();
    });
  }

  /// 播放提示音
  Future<void> playAudio() async {
    audioPlayer.play();
  }
}
